<template>
<div>
    <!-- 面包屑组件 -->
    <breadcrumb :navData="navData"></breadcrumb>

    <!-- Card 卡片 -->
    <el-card>
        <!-- 搜索框 -->
        <el-row :gutter="20">
            <el-col :span="8"><div class="grid-content bg-purple">
                <el-input placeholder="请输入内容" v-model="query" class="input-with-select">
                    <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
                </el-input>
            </div></el-col>
            <el-col :span="16"><div class="grid-content bg-purple-light">
                <el-button type="primary" @click="addDialog = true">添加用户</el-button>
            </div></el-col>
        </el-row>

        <!-- 列表 -->
        <el-table :data="list" border stripe style="width: 100%;">
            <el-table-column type="index" label="#">
            </el-table-column>
            <el-table-column prop="username" label="姓名">
            </el-table-column>
            <el-table-column prop="email" label="邮箱">
            </el-table-column>
            <el-table-column prop="mobile" label="电话">
            </el-table-column>
            <el-table-column prop="role_name" label="角色">
            </el-table-column>
            <el-table-column label="状态">
                <template slot-scope="scope">
                    <el-switch @change="changeState(scope.row)" v-model="scope.row.mg_state"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <!-- 编辑 -->
                    <el-button
                    size="mini"
                    type="primary"
                    icon="el-icon-edit"
                    @click="editOne(scope.row.id)"></el-button>
                    <!-- 删除 -->
                    <el-button
                    size="mini"
                    type="danger"
                    icon="el-icon-delete"
                    @click="delOne(scope.row.id)"></el-button>
                    <!-- 分配权限 -->
                    <el-tooltip class="item" effect="dark" content="分配权限" placement="top">
                      <el-button type="warning" size="mini" icon="el-icon-setting" @click="assignRoles(scope.row)"></el-button>
                    </el-tooltip>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>

        <!-- 添加模态框 -->
        <el-dialog
            title="添加用户"
            :visible.sync="addDialog"
            >
            <el-form :model="addForm" :rules="addRules" ref="addForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password" type="password">
                    <el-input v-model="addForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="mobile">
                    <el-input v-model="addForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialog = false">取 消</el-button>
                <el-button type="primary" @click="submitAddForm('addForm')">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑的模态框 --> 
        <el-dialog
            title="编辑用户"
            :visible.sync="editDialog"
            >
            <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="用户名" prop="username">
                    <el-input :disabled="true" v-model="editForm.username" ></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="mobile">
                    <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialog = false">取 消</el-button>
                <el-button type="primary" @click="submitEditForm('editForm')">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 分配权限的模态框 -->
        <el-dialog
          title="提示"
          :visible.sync="roleDialog"
        >
          <el-form :model="rolesForm" ref="rolesFormRef" label-width="100px">
                <!--用户名-->
                <el-form-item label="当前的用户:">
                    <span>{{rolesForm.username}}</span>
                    <!--<el-input disabled v-model="rolesForm.username"></el-input>-->
                </el-form-item>
                <!--角色-->
                <el-form-item label="当前的角色:">
                    <span>{{rolesForm.role_name}}</span>
                    <!--<el-input v-model="rolesForm.role_name"></el-input>-->
                </el-form-item>
                <!--新角色-->
                <el-form-item label="分配新角色:">
                    <el-select v-model="rolesForm.rid" placeholder="请选择">
                        <el-option
                            v-for="item in rolesOptions"
                            :key="item.id"
                            :label="item.roleName"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="roleDialog = false">取 消</el-button>
            <el-button type="primary" @click="onAddRole">确 定</el-button>
          </span>
        </el-dialog>
    </el-card>
</div>
</template>

<script>
export default {
  components: {},
  data() {
    return {
      //面包屑数据
      navData: ["用户管理", "用户列表"],
      list: [],
      query: "", //搜索的关键词 可以为空
      pagenum: 1, //当前的页码  默认是第1页  不可以为空
      pagesize: 5, //每页显示的条数 默认是5条   不可以为空
      total: 0, //总数量
      value1: false, //开关

      //分配权限的数据
      roleDialog: false, //分配权限
      rolesForm: {
        userId: "", //当前用户id
        username: "", //当前的用户
        role_name: "", //当前的角色
        rid: "" //新的角色ID
      },
      rolesOptions: [],

      //添加的数据
      addDialog: false, //添加的弹框
      addForm: {
        //添加的数据
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      addRules: {
        //添加的规则
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度在 6 到 15 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        mobile: [
          { required: true, message: "请输入电话号码", trigger: "blur" },
          {
            min: 11,
            max: 11,
            message: "手机号不正确,请重新输入",
            trigger: "blur"
          }
        ]
      },

      //编辑的数据
      usersId: "",
      editDialog: false,
      editForm: {
        //编辑的数据
        username: "",
        email: "",
        mobile: ""
      },
      editRules: {
        //编辑的规则
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        mobile: [
          { required: true, message: "请输入电话号码", trigger: "blur" },
          {
            min: 11,
            max: 11,
            message: "手机号不正确,请重新输入",
            trigger: "blur"
          }
        ]
      }
    };
  },

  methods: {
    //请求列表数据
    async getList() {
      let res = await this.$http.get("/users", {
        params: {
          query: this.query,
          pagenum: this.pagenum,
          pagesize: this.pagesize
        }
      });
      console.log("res_list", res);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.list = res.data.users;
      this.total = res.data.total;
    },

    //搜索
    search() {
      this.pagenum = 1;
      this.getList();
      this.query = "";
    },

    //点击确定添加
    submitAddForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          let res = await this.$http.post("/users", this.addForm);
          // console.log("add", res);
          if (res.meta.status == 201) {
            this.getList();
            this.addDialog = false;
            this.$message.success(res.meta.msg);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //点击编辑按钮
    async editOne(id) {
      this.editDialog = true;
      this.usersId = id;
      let res = await this.$http.get("/users/" + id);
      // console.log("res_edit", res);
      this.editForm = res.data;
    },
    //点击确定编辑
    submitEditForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          let res = await this.$http.put(
            "users/" + this.usersId,
            this.editForm
          );
          // console.log('editSure',res);
          if (res.meta.status == 200) {
            this.getList();
            this.editDialog = false;
            this.$message.success(res.meta.msg);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //点击分配权限
    //分配角色
    async assignRoles(item) {
      console.log("分配角色===>", item);
      this.rolesForm.userId = item.id;
      this.rolesForm.username = item.username;
      this.rolesForm.role_name = item.role_name;
      this.rolesForm.rid = "";
      let res = await this.$http.get("roles");
      console.log(res);
      this.rolesOptions = res.data;
      this.roleDialog = true;
    },
    //点击确定分配权限
    async onAddRole() {
      let rid = this.rolesForm.rid;
      if (!rid) {
        return this.$message.warning("请选择要分配的新角色！");
      }
      let res = await this.$http.put(`users/${this.rolesForm.userId}/role`, {
        rid
      });
      console.log("res", res);
      if (res.meta.status === 200) {
        //重新获取数据
        this.getList();
        this.$message.success(res.meta.msg);
        this.roleDialog = false;
      } else {
        this.$message.error(res.meta.msg);
      }
    },

    //点击删除
    delOne(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          let res = await this.$http.delete("users/" + id);
          // console.log('delOne',res);
          if (res.meta.status == 200) {
            this.getList();
            this.$message.success(res.meta.msg);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    //点击修改用户状态
    async changeState(row) {
      let res = await this.$http.put(`users/${row.id}/state/${row.mg_state}`);
      console.log("state", res);
      if (res.meta.status !== 200) {
        row.mg_state = !row.mg_state;
        return this.$message.error("修改状态失败");
      }
      this.$message.success(res.meta.msg);
    },

    //分页
    handleSizeChange(newSize) {
      this.pagesize = newSize;
      this.getList();
    },
    handleCurrentChange(current) {
      this.pagenum = current;
      this.getList();
    }
  },

  created() {
    this.getList();
  }
};
</script> 

<style  lang='scss' scoped>
</style>